﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmoneyWeiXinCommon;
using EmoneyWeiXinBLL;
using EmoneyWeiXinEntity;
using System.IO;
using System.Data;
using System.Configuration;
using EmoneyWeiXinThreadBLL;
using System.Threading;
using EmoneyWeiXin.Filter;
using Newtonsoft.Json.Linq;

namespace EmoneyWeiXin.Controllers
{
    public class ReportController : Controller
    {
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
        }
        //
        // GET: /Report/
        [LoginAuthorizeAttribute]
        public ActionResult Index()
        {
            return View();
        }

        //素材列表页面
        [LoginAuthorizeAttribute]
        public ActionResult NewsReportfbList()
        {
            ViewBag.leftid = int.Parse(Request["leftid"]);
            //查询栏目方法
            //var obj = MenuBLL.getMenuList(-1);
            //ViewBag.memulist = obj;
            return View();
        }
        //查询栏目方法
        public string GetMemuTypeList()
        {
            var weixinid = int.Parse(Request["weixinid"] == null ? "-1" : Request["weixinid"]);
            var uid = -1;
            UserEntity us = LoginUserInfo.GetLoginUserCache();
            if (us != null)
                uid = us.id;

            var obj = MenuBLL.getMenuList2(weixinid, uid);
            if (obj.Tables.Count > 0)
            {
                return JsonTools.ToJson(obj.Tables[0]);
            }
            else
            {
                return "";
            }
        }

        //查询素材列表方法
        public string QueryNewsReportfbList()
        {
            var pindex = int.Parse(Request["pindex"]);
            var psize = int.Parse(Request["psize"]);
            var memutype = Request["memutype"];
            var pubdate1 = Request["pubdate1"];
            var pubdate2 = Request["pubdate2"];
            var total = 0;
            var uid = -1;
            UserEntity us = LoginUserInfo.GetLoginUserCache();
            if (us != null)
                uid = us.id;
            var obj = NewsReportManager.getNewsReportfbList(pindex, psize, out total, memutype, pubdate1, pubdate2, us.id);
            return total.ToString() + "^" + JsonTools.ToJson(obj);
        }


        public ActionResult MenuReportMerge()
        {
            string weixinid = Request["weixinid"] == null ? "-1" : Request["weixinid"];
            string menuType = Request["menutype"];
            string newsReportsIds = Request["newsreportid"];
            List<string> newsIdArry;
            if (newsReportsIds != "")
            {
                newsIdArry = newsReportsIds.Split(',').ToList();
            }
            else
            {
                newsIdArry = new List<string>();
            }
            MenuReportMergeBLL bll = new MenuReportMergeBLL();
            try
            {
                bll.Insert(menuType, newsIdArry, weixinid);
                if (newsIdArry.Count == 0) //表示解散合并，移除缓存中的数据
                {
                    MemcachedTools1 mmtools = new MemcachedTools1();
                    string vipNewsMMKey = StringTools.ChangeRealKey("MenuReportMerge", weixinid + menuType);
                    mmtools.Remove(vipNewsMMKey);
                }
                return Content("1");
            }
            catch (Exception)
            {
                return Content("0");
            }


        }
        [LoginAuthorizeAttribute]
        //素材编辑页面
        public ActionResult NewsReportfbEdit()
        {
            ViewBag.leftid = int.Parse(Request["leftid"]);
            var weixinid = int.Parse(Request["weixinid"] == null ? "-1" : Request["weixinid"]);
            //var obj = MenuBLL.getMenuList(weixinid);
            var uid = -1;
            UserEntity us = LoginUserInfo.GetLoginUserCache();
            if (us != null)
                uid = us.id;

            var obj = MenuBLL.getMenuList2(weixinid, uid);
            ViewBag.memulist = obj;
            var id = 0;
            var objID = Request["id"];
            if (!string.IsNullOrEmpty(objID))
            {
                id = int.Parse(objID);
            }
            var pt = Request["pt"];
            if (pt == "1")
            {
                var newsfb = NewsReportManager.getNewsReportByID(id);
                var nptype = newsfb.MemuType;
                ViewBag.model = newsfb;
                ViewBag.nptype = nptype;
            }
            else
            {
                var newsfb = NewsReportManager.getNewsReportfbByID(id);
                var nptype = newsfb.MemuType;
                ViewBag.model = newsfb;
                ViewBag.nptype = nptype;
            }

            ViewBag.id = id;
            ViewBag.pt = pt;

            return View();
        }
        [LoginAuthorizeAttribute]
        //素材保存方法
        [ValidateInput(false)]
        public ActionResult uploadNews()
        {
            this.ValidateRequest = false;
            bool uploadSuccess = true;
            string imgurl = "";
            #region 上传缩略图
            HttpPostedFileBase file = Request.Files["file"];
            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    var filename = file.FileName;
                    filename = Guid.NewGuid().ToString() + ".jpg";

                    byte[] input = new byte[file.ContentLength];
                    file.InputStream.Read(input, 0, file.ContentLength);
                    HttpUploadFile fileUp = new HttpUploadFile();
                    string result = fileUp.UploadFile(Config.fileuploadUrl, Config.ModuleName, filename, input);//b：byte[]类型（上传文件的文件流）
                    //result={"state":"success","url":"http://192.168.8.102/down/emoney_weixin_news/2014/5/20140523124440Hydrangeas.jpg","msg":"成功上传"}
                    var obj = JsonTools.ToObject<uploadEntity>(result);
                    var state = obj.state;
                    if (state == "success")
                    {
                        imgurl = obj.url;
                    }
                    else uploadSuccess = false;
                }
                catch (Exception)
                {
                    uploadSuccess = false;
                }
            }
            #endregion
            if (uploadSuccess)
            {
                NameValueCollection form = Request.Form;
                var leftid = getForm(form, "hdleftid");
                var nptype = getForm(form, "hdnptype");
                nptype = getForm(form, "drpNewsType");
                #region 填充model
                int id = Common.StrToInt(getForm(form, "hdnid"));
                //var pt = Request["pt"];//pt=1表示修改资讯表否则是修改素材表
                var pt = getForm(form, "hdnpt");
                if (pt == "1")
                {
                    NewsReportEntity news;
                    if (id != 0)
                    {
                        news = NewsReportManager.getNewsReportByID(id);
                    }
                    else news = new NewsReportEntity();

                    news.MemuType = nptype;
                    news.source = getForm(form, "drpSource");
                    news.title = getForm(form, "txtTitle");
                    news.Author = getForm(form, "txtAuthor");
                    if (imgurl != "") news.ImageUrl = imgurl;
                    news.Summary = getForm(form, "txtSummary");

                    news.Content = form["txtContent"].ToString();
                    news.Content = getForm(form, "txtContent");
                    news.OutsideUrl = getForm(form, "txtOutsideUrl");
                    news.PubStatus = Common.StrToInt(getForm(form, "drpPubStatus"), 1);
                    news.PubMethod = getForm(form, "drpPubMethod"); ;
                    news.pubDate = DateTime.Now;
                    news.createtime = DateTime.Now;
                    news.updatetime = DateTime.Now;
                    news.isvalid = 1;
                    bool saveSuccess = false;
                    try
                    {
                        saveSuccess = NewsReportManager.UpdateNewsReport(news) > 0 ? true : false;
                    }
                    catch (Exception)
                    {
                        saveSuccess = false;
                    }
                    if (saveSuccess)
                        return Redirect("NewsReportList?ntype=" + nptype.ToString() + "&leftid=" + leftid);
                }
                else
                {
                    NewsReportfbEntity news;
                    if (id != 0)
                    {
                        news = NewsReportManager.getNewsReportfbByID(id);
                    }
                    else news = new NewsReportfbEntity();
                    news.MemuType = nptype;
                    news.source = getForm(form, "drpSource");
                    news.title = getForm(form, "txtTitle");
                    news.Author = getForm(form, "txtAuthor");
                    if (imgurl != "") news.ImageUrl = imgurl;
                    news.Summary = getForm(form, "txtSummary");
                    news.Content = form["txtContent"].ToString();
                    //news.Content = getForm(form, "txtContent");
                    news.OutsideUrl = getForm(form, "txtOutsideUrl");
                    news.PubStatus = Common.StrToInt(getForm(form, "drpPubStatus"), 1);
                    news.PubMethod = getForm(form, "drpPubMethod"); ;
                    news.pubDate = DateTime.Now;
                    news.createtime = DateTime.Now;
                    news.updatetime = DateTime.Now;
                    news.isvalid = 1;
                    bool saveSuccess = false;
                    try
                    {
                        saveSuccess = NewsReportManager.UpdateNewsReportfb(news) > 0 ? true : false;


                    }
                    catch (Exception)
                    {
                        saveSuccess = false;
                    }
                    if (saveSuccess)
                    {
                        //写缓存
                        EmoneyWeiXinThreadBLL.ThreadWeiXinBLL.getNewsReportCache();
                        var url = EmoneyWeiXinCommon.StringTools.GetTrendsFile("Report/NewsReportfbList");
                        if (news.MemuType == ConstName.VipZixunName && news.PubStatus == 3)
                        {
                            //如果为vip咨询，并且咨询发布状态为已发布，那么移除缓存中的vip咨询
                            MemcachedTools1 mmtools = new MemcachedTools1();
                            string vipNewsMMKey = StringTools.ChangeRealKey("vipNewsMMKey", "");
                            mmtools.Remove(vipNewsMMKey);
                        }
                        return Redirect(url + "?ntype=" + nptype.ToString() + "&leftid=" + leftid);
                    }
                }

                #endregion

                //else //报错
            }//报错 
            return View();
        }
        //素材状态更新方法
        public string UpdateValidNewsReportfb()
        {
            var id = int.Parse(Request["id"]);
            var valid = Request["isvalid"] == "1" ? "0" : "1";
            var isvalid = int.Parse(valid);
            var ir = NewsReportManager.UpdateValidNewsReportfb(id, isvalid);
            if (ir > 0)
            {
                return "1";
            }
            else { return ""; }
        }
        public string getForm(NameValueCollection form, string k)
        {
            if (form[k] != null) return form[k].ToString();
            else return "";
        }


        //资讯列表页面
        public ActionResult NewsReportList()
        {
            ViewBag.leftid = int.Parse(string.IsNullOrEmpty(Request["leftid"]) ? "20" : Request["leftid"]);
            return View();
        }
        //查询资讯列表方法
        public string QueryNewsReportList()
        {
            var pindex = int.Parse(Request["pindex"]);
            var psize = int.Parse(Request["psize"]);
            var memutype = Request["memutype"];
            var pubdate1 = Request["pubdate1"];
            var pubdate2 = Request["pubdate2"];
            var title = Request["title"];
            var weixinid = int.Parse(Request["weixinid"]);
            var total = 0;
            var obj = NewsReportManager.getNewsReportList(pindex, psize, out total, memutype, pubdate1, pubdate2, title, weixinid);
            return total.ToString() + "^" + JsonTools.ToJson(obj);
        }
        public string QueryNewsReportList2()
        {
            var pindex = int.Parse(Request["pindex"]);
            var psize = int.Parse(Request["psize"]);
            var memutype = Request["memutype"];
            var pubdate1 = Request["pubdate1"];
            var pubdate2 = Request["pubdate2"];
            var title = Request["title"];
            var weixinid = int.Parse(Request["weixinid"]);
            var total = 0;
            var obj = NewsReportManager.getNewsReportList2(pindex, psize, out total, memutype, pubdate1, pubdate2, title, weixinid);
            return total.ToString() + "^" + JsonTools.ToJson(obj);
        }
        //资讯状态更新方法
        public string UpdateValidNewsReport()
        {
            var id = int.Parse(Request["id"]);
            var valid = Request["isvalid"] == "1" ? "0" : "1";
            var isvalid = int.Parse(valid);
            var ir = NewsReportManager.UpdateValidNewsReport(id, isvalid);
            if (ir > 0)
            {
                return "1";
            }
            else { return ""; }
        }

        //资讯选择页
        public ActionResult NewsReportListSelected()
        {
            ViewBag.weixinid = Request["weixinid"];
            ViewBag.DfBeginDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
            ViewBag.DfEndDate = DateTime.Now.ToString("yyyy-MM-dd");
            return View();
        }
        [LoginAuthorizeAttribute]
        //资讯详细页面
        public ActionResult NewsReportfbDetail()
        {
            var pt = Request["pt"];
            var id = int.Parse(Request["id"]);
            if (pt == "1")
            {
                var obj = NewsReportManager.getNewsReportByID(id);
                weixinUserBLL wu = new weixinUserBLL();
                var weixin = wu.getWeixinUserByID(obj.weixinid);
                ViewBag.weixinname = weixin.title;
                ViewBag.newsmodel = obj;
                var menulist = MenuBLL.getMenuList();
                menulist = menulist.Where(p => p.everyKey == obj.MemuType).ToList();
                if (menulist != null && menulist.Count > 0)
                {
                    ViewBag.contentym = menulist[0].contentym;
                    ViewBag.contentyj = menulist[0].contentyj;
                }
            }
            else
            {
                var obj = NewsReportManager.getNewsReportfbByID(id);
                ViewBag.weixinname = "";
                ViewBag.newsmodel = obj;
                ViewBag.contentym = "";
                ViewBag.contentyj = "";
            }
            ViewBag.newsreportnum = 32;
            ViewBag.strUserzan = 56;
            return View();
        }
        //刷新token
        public ActionResult RefreshToken()
        {
            try
            {
                string weixinid = Request["weixinid"];
                string keys = StringTools.ChangeRealKey("weixinUser", weixinid);
                MemcachedTools1 mmtools = new MemcachedTools1();
                var obj = mmtools.Get(keys);
                weixinUserEntity weixinuser = JsonTools.ToObject<weixinUserEntity>(obj.ToString());
                var key = Config.MemcachedKey + ".TokenHelper.GetToken." + weixinuser.AppId;
                MemcachedTools.Clear(key);
                TokenHelper.GetToken(weixinuser.AppId, weixinuser.AppSecret);
                return Content("刷新成功");
            }
            catch (Exception ex)
            {
                MyTrace.get().add(ex.Message);
                return Content("刷新失败");
            }
        }


        //推送vip解盘数据
        public string TSVipJiePanNews()
        {
            string newsreportid = Request.QueryString["newsreportid"];
            string weixinid = Request.QueryString["weixinid"];
            string groupId = Request["groupId"];
            UserEntity us = LoginUserInfo.GetLoginUserCache();
            if (us == null || string.IsNullOrEmpty(us.Username))
            {
                return "-99";
            }
            MemcachedTools1 mmtools = new MemcachedTools1();
            string keys = "";

            string strResult = "";
            if (!string.IsNullOrEmpty(newsreportid) && !string.IsNullOrEmpty(weixinid))
            {
                keys = StringTools.ChangeRealKey("weixinUser", weixinid);
                var obj = mmtools.Get(keys);
                string strtoken = "";
                weixinUserEntity weixinuser = new weixinUserEntity();
                if (obj != null)
                {
                    weixinuser = JsonTools.ToObject<weixinUserEntity>(obj.ToString());

                    if (weixinuser != null && weixinuser.id > 0)
                    {
                        strtoken = TokenHelper.GetToken(weixinuser.AppId, weixinuser.AppSecret);
                    }
                    else
                    {
                        if (ThreadWeiXinBLL.listweixinUser == null || ThreadWeiXinBLL.listweixinUser.Count < 0)
                        {
                            ThreadWeiXinBLL.getWeixinUser();
                        }
                        if (ThreadWeiXinBLL.listweixinUser != null && ThreadWeiXinBLL.listweixinUser.Count > 0)
                        {
                            var query = ThreadWeiXinBLL.listweixinUser.Where(x => x.id == Convert.ToInt32(weixinid)).ToList();
                            if (query != null && query.Count > 0)
                            {
                                if (!string.IsNullOrEmpty(query[0].AppId) && !string.IsNullOrEmpty(query[0].AppSecret))
                                {
                                    strtoken = TokenHelper.GetToken(query[0].AppId, query[0].AppSecret);
                                }
                            }
                        }
                    }
                }
                string[] strArr = newsreportid.Split(',');
                MemcachedTools mmtols = new MemcachedTools();
                List<NewsReportEntity> list = new List<NewsReportEntity>();
                NewsReportManager newsbll = new NewsReportManager();
                string strid = "";
                for (int i = 0; i < strArr.Length; i++)
                {
                    keys = StringTools.ChangeRealKey("newsreport", weixinid + strArr[i]);
                    var query = mmtools.Get(keys);
                    if (query != null)
                    {
                        list.Add(JsonTools.ToObject<NewsReportEntity>(query.ToString()));
                        if (strid != "")
                        {
                            strid += "*^&" + list[list.Count - 1].ID;
                        }
                        else
                        {
                            strid += list[list.Count - 1].ID;
                        }
                    }
                    else
                    {
                        var sc = newsbll.getNewsReportOne(strArr[i]);
                        if (sc != null && sc.ID > 0)
                        {
                            keys = StringTools.ChangeRealKey("newsreport", weixinid + strArr[i]);
                            mmtools.Add(keys, JsonTools.ToJson(sc), 24 * 365, 0, 0);

                            list.Add(sc);

                            if (strid != "")
                            {
                                strid += "*^&" + sc.ID;
                            }
                            else
                            {
                                strid += sc.ID;
                            }
                        }
                    }
                }
                weixinUserBLL weixinbll = new weixinUserBLL();
                var querystockuser = weixinbll.GetGroupUserAt48HHy(weixinid, groupId);
                for (int i = 0; i < list.Count; i++)
                {
                    string strJson = string.Empty;
                    if (string.IsNullOrEmpty(list[i].ImageUrl))
                    {
                        strJson = StringTools.GetSendWbJson(list[i].Summary);
                    }
                    else
                    {
                        strJson = StringTools.GetNewsPortJson(new List<NewsReportEntity>() { list[i] });
                    }
                    if (querystockuser != null && querystockuser.Count > 0)
                    {
                        foreach (StockDoctorloguserEntity item in querystockuser)
                        {
                            string tojson1 = strJson.Replace("{0}", item.FromUserName).Replace("{[openid]}", item.FromUserName);
                            tojson1 = tojson1.Replace("{1}", weixinid);
                            ThreadPolPicTuiSongDTW thread = new ThreadPolPicTuiSongDTW(tojson1, strtoken, item.FromUserName, strid, Convert.ToInt32(weixinid), 4);
                            ThreadPool.QueueUserWorkItem(new WaitCallback(thread.ThreadProc), thread);
                        }
                        strResult = querystockuser.Count.ToString();
                    }

                }

            }
            else
            {
                strResult = "-1";
            }
            return strResult;
        }


        //推送48小时
        public string TSNewsReportUser()
        {
            string newsreportid = Request.QueryString["newsreportid"];
            string weixinid = Request.QueryString["weixinid"];
            UserEntity us = LoginUserInfo.GetLoginUserCache();
            if (us == null || string.IsNullOrEmpty(us.Username))
            {
                return "-99";
            }
            MemcachedTools1 mmtools = new MemcachedTools1();
            string keys = "";

            string strResult = "";
            if (!string.IsNullOrEmpty(newsreportid) && !string.IsNullOrEmpty(weixinid))
            {
                keys = StringTools.ChangeRealKey("weixinUser", weixinid);
                var obj = mmtools.Get(keys);
                string strtoken = "";
                weixinUserEntity weixinuser = new weixinUserEntity();
                if (obj != null)
                {
                    weixinuser = JsonTools.ToObject<weixinUserEntity>(obj.ToString());

                    if (weixinuser != null && weixinuser.id > 0)
                    {
                        strtoken = TokenHelper.GetToken(weixinuser.AppId, weixinuser.AppSecret);
                    }
                    else
                    {
                        if (ThreadWeiXinBLL.listweixinUser == null || ThreadWeiXinBLL.listweixinUser.Count < 0)
                        {
                            ThreadWeiXinBLL.getWeixinUser();
                        }
                        if (ThreadWeiXinBLL.listweixinUser != null && ThreadWeiXinBLL.listweixinUser.Count > 0)
                        {
                            var query = ThreadWeiXinBLL.listweixinUser.Where(x => x.id == Convert.ToInt32(weixinid)).ToList();
                            if (query != null && query.Count > 0)
                            {
                                if (!string.IsNullOrEmpty(query[0].AppId) && !string.IsNullOrEmpty(query[0].AppSecret))
                                {
                                    strtoken = TokenHelper.GetToken(query[0].AppId, query[0].AppSecret);
                                }
                            }
                        }
                    }
                }
                string[] strArr = newsreportid.Split(',');
                MemcachedTools mmtols = new MemcachedTools();
                List<NewsReportEntity> list = new List<NewsReportEntity>();
                NewsReportManager newsbll = new NewsReportManager();
                string strid = "";
                for (int i = 0; i < strArr.Length; i++)
                {
                    keys = StringTools.ChangeRealKey("newsreport", weixinid + strArr[i]);
                    var query = mmtools.Get(keys);
                    if (query != null)
                    {
                        list.Add(JsonTools.ToObject<NewsReportEntity>(query.ToString()));
                        if (strid != "")
                        {
                            strid += "*^&" + list[list.Count - 1].ID;
                        }
                        else
                        {
                            strid += list[list.Count - 1].ID;
                        }
                    }
                    else
                    {
                        var sc = newsbll.getNewsReportOne(strArr[i]);
                        if (sc != null && sc.ID > 0)
                        {
                            keys = StringTools.ChangeRealKey("newsreport", weixinid + strArr[i]);
                            mmtools.Add(keys, JsonTools.ToJson(sc), 24 * 365, 0, 0);

                            list.Add(sc);

                            if (strid != "")
                            {
                                strid += "*^&" + sc.ID;
                            }
                            else
                            {
                                strid += sc.ID;
                            }
                        }
                    }
                }

                string strJson = getNewsPortJson(list);
                weixinUserBLL weixinbll = new weixinUserBLL();
                var querystockuser = weixinbll.getStockdoctordUser(weixinid);
                if (querystockuser != null && querystockuser.Count > 0)
                {
                    foreach (StockDoctorloguserEntity item in querystockuser)
                    {
                        string tojson1 = strJson.Replace("{0}", item.FromUserName).Replace("{[openid]}", item.FromUserName);
                        tojson1 = tojson1.Replace("{1}", weixinid);
                        ThreadPolPicTuiSongDTW thread = new ThreadPolPicTuiSongDTW(tojson1, strtoken, item.FromUserName, strid, Convert.ToInt32(weixinid), 4);
                        ThreadPool.QueueUserWorkItem(new WaitCallback(thread.ThreadProc), thread);
                    }
                    strResult = querystockuser.Count.ToString();
                }
            }
            else
            {
                strResult = "-1";
            }
            return strResult;
        }

        public static string getStringstr(string str)
        {
            string strContext = "";
            strContext += "{";
            strContext += "\"touser\":\"{0}\",";
            strContext += "\"msgtype\":\"text\",";
            strContext += "\"text\":";
            strContext += "{";
            strContext += "\"content\":\"" + str + "\"";
            strContext += "}}";
            return strContext;
        }

        /// <summary>
        /// 推送json数据拼接
        /// </summary>
        /// <param name="newsr"></param>
        /// <returns></returns>
        public string getNewsPortJson(List<NewsReportEntity> Listnewsr)
        {
            string strContext = "";
            if (Listnewsr != null && Listnewsr.Count > 0)
            {
                if (Listnewsr.Count == 1 && string.IsNullOrEmpty(Listnewsr[0].ImageUrl))
                {
                    return getStringstr(Listnewsr[0].Summary);
                }
                strContext += "{";
                strContext += "\"touser\":\"{0}\",";
                strContext += "\"msgtype\":\"news\",";
                strContext += "\"news\":{";
                strContext += "\"articles\": [";

                for (int i = 0; i < Listnewsr.Count; i++)
                {
                    strContext += "{";
                    strContext += "\"title\":\"" + Listnewsr[i].title + "\",";
                    strContext += "\"description\":\"" + Listnewsr[i].Summary + "\",";
                    if (!string.IsNullOrEmpty(Listnewsr[i].OutsideUrl))
                    {
                        if (Listnewsr[i].OutsideUrl.Contains("?"))
                        {
                            strContext += "\"url\":\"" + Listnewsr[i].OutsideUrl + "&fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                        }
                        else
                        {
                            strContext += "\"url\":\"" + Listnewsr[i].OutsideUrl + "?fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                        }
                    }
                    else
                    {
                        strContext += "\"url\":\"" + Config.selNewsReportUrl + "?fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                    }
                    strContext += "\"picurl\":\"" + Listnewsr[i].ImageUrl + "\"";
                    strContext += "}";

                    if (i != Listnewsr.Count - 1)
                    {
                        strContext += ",";
                    }
                }
                strContext += "]";
                strContext += "}";
                strContext += "}";
            }
            return strContext;
        }

        /// <summary>
        /// 微信后台图文素材列表
        /// </summary>
        /// <returns></returns>
        public ActionResult HtTwSucaiList()
        {
            return View();
        }

        public ActionResult GetHtTwSucaiList()
        {
            int index = int.Parse(Request["pindex"]);
            int pageSize = int.Parse(Request["psize"]);
            int weixinId = int.Parse(Request["weixinid"]);
            string type = "news";
            weixinUserBLL weixinuserBll = new weixinUserBLL();
            weixinUserEntity info = weixinuserBll.GetWeixinUserFromCache(weixinId.ToString());
            string appId = info.AppId;
            string secret = info.AppSecret;
            string url = string.Format(Config.WeiXin_ApiUrl + "material/batchget_material?access_token={0}", TokenHelper.GetToken(appId, secret));
            string jsonData = "{\"type\":\"" + type + "\",\"offset\":" + pageSize * (index - 1) + ",\"count\":" + pageSize + "}";
            string resultJson = NetHelper.LoadDataPost(url, null, jsonData, System.Text.Encoding.UTF8);
            if (resultJson.Contains("40001"))
            {
                TokenHelper.ClearToken(appId);
            }
            Batchget_MaterialEntity resultEntity = JsonTools.ToObject<Batchget_MaterialEntity>(resultJson);
            if (resultEntity != null && resultEntity.item != null)
            {   
                List<Batchget_Item> itemLst = resultEntity.item;
                foreach (var item in itemLst)
                {
                    string tempStr = string.Empty;
                    foreach (var item2 in item.content.news_item)
                    {
                        tempStr += item2.title + "\n";
                    }
                    item.allTitle = tempStr;
                    DateTime date = new DateTime(1970, 1, 1, 0, 0, 0);
                    date = date.AddSeconds(double.Parse(item.update_time));
                    item.update_time = date.Year + "-" + date.Month + "-" + date.Day;
                }
                string retunnJson = JsonTools.ToJson(new { total = resultEntity.total_count, list = itemLst });
                return Content(retunnJson);
            }
            else
            {
                return Content("");
            }
        }
        /// <summary>
        /// 群发至指定分组
        /// </summary>
        /// <returns></returns>
        public ActionResult QunFaSendToGroup()
        {
            string groupId = Request["groupid"];
            string mediaId = Request["mediaId"];
            string weixinid = Request["weixinid"];
            weixinUserBLL weixinuserBll = new weixinUserBLL();
            //从缓存中获取该微信号的信息
            weixinUserEntity info = weixinuserBll.GetWeixinUserFromCache(weixinid);
            string appId = info.AppId;
            string secret = info.AppSecret;
            string url = string.Format(Config.WeiXin_ApiUrl + "message/mass/sendall?access_token={0}", TokenHelper.GetToken(appId, secret));
            string jsonData = string.Empty;
            if (groupId == "-1")
            {
                jsonData = "{\"filter\":{\"is_to_all\":true},\"mpnews\":{ \"media_id\":\"" + mediaId + "\"},\"msgtype\":\"mpnews\"}";
            }
            else
            {
                UserGroupManagerEntity entity = UserGroupManagerBLL.GetOne(groupId);
                int wx_groupId = entity.wx_groupid; //获取到该分组对应的微信后台的组别id
                jsonData = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"" + wx_groupId + "\"},\"mpnews\":{ \"media_id\":\"" + mediaId + "\"},\"msgtype\":\"mpnews\"}";
            }

            string json = NetHelper.LoadDataPost(url, null, jsonData, System.Text.Encoding.UTF8);
            if (json.Contains("send job submission success"))
            {
                return Content("发送任务已经提交成功");
            }
            else
            {
                JObject jObj = JObject.Parse(json);
                if (jObj != null)
                {
                    JToken jToken;
                    if (jObj.TryGetValue("errmsg", out jToken))
                    {
                        string funcRet = jObj["errmsg"].ToString().Replace("\"", "");
                        ////MyTrace.get().add("调用web服务器-GetTwoCodeTicket-errcode=" + funcRet);
                        return Content(funcRet);
                    }
                }
            }

            return View();
        }
    }


}
